package ext.tianma.vProductJurisdiction;

import java.io.File;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Enumeration;

import ext.tianma.db.ConnectionFactory;
import ext.tianma.util.PropertiesUtil;
import wt.fc.PersistenceHelper;
import wt.fc.QueryResult;
import wt.inf.container.ExchangeContainer;
import wt.inf.container.WTContainerHelper;
import wt.org.OrganizationServicesHelper;
import wt.org.WTGroup;
import wt.org.WTOrganization;
import wt.org.WTUser;
import wt.pds.StatementSpec;
import wt.query.QueryException;
import wt.query.QuerySpec;
import wt.query.SearchCondition;
import wt.session.SessionHelper;
import wt.session.SessionServerHelper;
import wt.util.WTException;

public class VProductJurisdictionProcessor {

	private static String configFilePath = "codebase" + File.separator + "ext" + File.separator + "tianma"
			+ File.separator + "cfg" + File.separator + "TianmaPro.properties";

	/***
	 * 根据审阅对象获取相关信息
	 * 
	 * @param userName
	 * @return
	 * @throws WTException
	 */
	public static String getAuditRecord() throws WTException {
		boolean flag = SessionServerHelper.manager.setAccessEnforced(false); //取消权限验证
		
		WTUser user1 = (WTUser) SessionHelper.manager.getPrincipal();
		String userName = user1.getFullName();
		System.out.println("user1.getName()===>>" + user1.getName());
		String ipAdress = "";
		ConnectionFactory cf = ConnectionFactory.getInstance();
		Connection conn = cf.getConnection();
		PreparedStatement pstmt = null;
		String sql = null;
		ResultSet rs = null;
		System.out.println("userName========>>" + userName);
		try {
			if (userName == null) {
				sql = "SELECT *  FROM (SELECT *  FROM Auditrecord  ORDER BY updatestampa2 DESC) WHERE ROWNUM = 1";
			} else {
				sql = "SELECT *  FROM (SELECT *  FROM Auditrecord WHERE username like ? and eventlabel='Context Logon' ORDER BY updatestampa2 DESC) WHERE ROWNUM = 1";
				pstmt = conn.prepareStatement(sql);
				pstmt.setString(1, "%" + userName + "%");
			}
			System.out.println("sql===>>>" + sql);
			rs = pstmt.executeQuery();
			System.out.println("pstmt1===>>>" + rs.next());
			String ipAddress = rs.getString("IPADDRESS");
			System.out.println("ipAddress====>>>" + ipAddress);
			if (ipAddress == null) {
				return "";
			} else {
				String username = rs.getString("username");
				System.out.println("endtime1====>>>" + username);
				String targetName = rs.getString("targetname");
				System.out.println("targetName====>>>" + targetName);
				PropertiesUtil ut = new PropertiesUtil(configFilePath);
				String ip = ut.getValueByKey("V项目.ip");
				System.out.println("ip=====>>>" + ip);
				WTGroup group = null;
				group = getGroupForName("V项目组");
				if (group == null) {
					throw new WTException("项目组不存在，请联系管理员新建！");
				} else {
					WTUser user = getUserByFullName(userName);
					System.out.println("user===>>"+user.getFullName());
					if (user != null) {
						if (ip.contains(ipAddress)) {
							group.addMember(user);
						} else {
							group.removeMember(user);
						}
					}
				}
				PersistenceHelper.manager.refresh(group);
				SessionServerHelper.manager.setAccessEnforced(flag); //恢复权限验证!
				System.out.println("====>>用户组更新完成");
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			cf.close(rs, pstmt, conn);
		}
		return ipAdress;
	}

	/***
	 * gx 将用户移动到固定角色
	 * 
	 * @throws WTException
	 */
	public static void moveUserToRole(WTUser user, String IPAdress) throws WTException {
		WTGroup group = null;
		// 根据组名获取当前组
		group = getGroupForName("IP授权");
		// 根据不同的IP将用户分配到不同的组
		if (IPAdress.equals("192.1681.1.")) {
			group.addMember(user);
		} else {
			group.removeMember(user);
		}
		PersistenceHelper.manager.refresh(group);
		System.out.println("====>>用户组更新完成");
	}

	/**
	 * 搜索群组
	 * 
	 * @param name
	 * @return
	 * @throws WTException
	 */
	public static QueryResult getGroup(String name) throws WTException {
		QuerySpec qs = new QuerySpec(WTGroup.class);
		qs.appendWhere(new SearchCondition(WTGroup.class, WTGroup.NAME, SearchCondition.EQUAL, name), new int[] { 0 });
		return PersistenceHelper.manager.find((StatementSpec) qs);
	}

	/**
	 * 根据组名得到组 gx
	 * 
	 * @param groupName
	 * @return
	 * @throws WTException
	 */
	public static WTGroup getGroupForName(String groupName) throws WTException {

		ExchangeContainer exchangecontainer = WTContainerHelper.service.getExchangeContainer();

		WTOrganization wtorganization = exchangecontainer.getOrganization();

		WTGroup group = null;
		group = OrganizationServicesHelper.manager.getGroup(groupName, wtorganization);// 组织下的组

		if (group == null) {

			group = OrganizationServicesHelper.manager.getGroup(groupName, exchangecontainer.getContextProvider());// 站点下的组

		}
		if (group == null) {
			throw new WTException("没有找到组: [" + groupName + "] ");
		}
		return group;
	}

	public static WTUser getUserByFullName(String fullName) throws WTException {
		Enumeration users = OrganizationServicesHelper.manager.findLikeUser("fullName", fullName);
		while (users.hasMoreElements()) {
			Object obj = users.nextElement();
			if (obj instanceof WTUser) {
				WTUser wtuser = (WTUser) obj;
				return wtuser;
			}
		}
		return null;
	}
}
